package com.mlz.mlzmall.ui.activity.act.personal;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.AgainLoginService;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.RequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.DataSharedPress;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.CacheUtils;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/18.
 */

public class MyInfoActivity extends VolleyBaseActivity implements View.OnClickListener {

    private LinearLayout rlChangeName;//修改名称
    private LinearLayout rlChangeMyAttr;//修改个人属性
    private LinearLayout rlChangePwd;//修改密码
    private TextView tvMyName;//我的名字
    private Button btnExit;//退出
    private TopTitleView centerUserinfoTopTitle;
    DataSharedPress sharedPress;
    private String phoneId;
    ACache mCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_info);//个人信息界面
        mCache = ACache.get(getApplication());
        phoneId = mCache.getAsString("phoneid");

        sharedPress = DataSharedPress.getSharedPress(getApplication(), phoneId);
        initView();
        setViewContent();
        setViewClickListener();
        initData();
    }

    private void initView() {
        rlChangeName = (LinearLayout) findViewById(R.id.rl_change_name);
        rlChangeMyAttr = (LinearLayout) findViewById(R.id.rl_change_my_attr);
        rlChangePwd = (LinearLayout) findViewById(R.id.rl_change_pwd);
        tvMyName = (TextView) findViewById(R.id.tv_my_name);
        centerUserinfoTopTitle = (TopTitleView) findViewById(R.id.center_userinfo_top_title);
        btnExit = (Button) findViewById(R.id.btn_exit);
    }

    private void setViewContent() {
        centerUserinfoTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        centerUserinfoTopTitle.setTitleButtonContent("个人信息", null, null);
    }

    private void setViewClickListener() {
        centerUserinfoTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                MyInfoActivity.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
            }
        });
        rlChangeName.setOnClickListener(this);
        rlChangePwd.setOnClickListener(this);
        rlChangeMyAttr.setOnClickListener(this);
        btnExit.setOnClickListener(this);
    }

    private void initData() {
        tvMyName.setText(sharedPress.getString("fullname"));
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.rl_change_name://修改名称的监听
                intent = new Intent(MyInfoActivity.this, ChangeNameActivity.class);
                startActivityForResult(intent, 101);
                break;
            case R.id.rl_change_my_attr://修改个人属性的监听
                intent = new Intent(MyInfoActivity.this, PersonalAttrActivity.class);
                startActivityForResult(intent, 201);
                break;
            case R.id.rl_change_pwd://修改密码的监听
                intent = new Intent(MyInfoActivity.this, ChangePwdActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_exit://退出登录的监听
                // 登出
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // 创建一个restTemplate 对象
                            RestTemplate restTemplate = new RestTemplate();
                            // 获取 sessionKey

                            String sessionKeyLogin = mCache.getAsString("sessionKeyLogin");

                            HttpHeaders requestHeaders = new HttpHeaders();
                            // 设置请求头
                            requestHeaders.set("Cookie", "JSESSIONID=" + sessionKeyLogin);
                            // 把请求头放在请求实体里
                            HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
                            ResponseEntity<String> cartInfo = restTemplate.exchange(URL.CUSTOMER.LOGOUT, HttpMethod.GET, requestEntity, String.class);

                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (mCache.getAsString("sessionKeyLogin") != null) {
                                StringTools.updatashopping = 123400;
                                mCache.remove("sessionKeyLogin");
                                mCache.remove("sessionKeyAuth");
                                mCache.remove("phoneid");

                                Log.i("111111111111",mCache.getAsString("sessionKeyLogin")+mCache.getAsString("sessionKeyAuth")+mCache.getAsString("phoneid"));
                            }
                        }

                    }
                }).start();

                CacheUtils.putBoolean(MyInfoActivity.this, "Logined", false);
                Intent intentLoginOut = new Intent().setClass(MyInfoActivity.this, PersonalActivity.class);
                startActivity(intentLoginOut.putExtra("LoginOut", true));

                Intent intent1 = new Intent(MyInfoActivity.this, AgainLoginService.class);
                stopService(intent1);
                sendBroadcast(new Intent("OUTLOGIN"));

                finish();
                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                break;
        }
        MyInfoActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            getUserInfo();

        }
    }

    //获取标签
    private void getUserInfo() {
        tag = "rGet";
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("telephone", isNull(MyApplication.getInstace().getLoginUser().getAccout()));

        JSONObject jsonObject = new JSONObject(param1);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.CUSTOMER.INFO, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.e(tag, jsonObject.toString());
                UserBean userBean = RequestUtils.userInfOnResponse(jsonObject.toString());//保存用户信息
                MyApplication.getmInstance().setLoginUser(userBean);
                tvMyName.setText(isNull(MyApplication.getInstance().getLoginUser().getUserName()));
                LogUtils.d(isNull(MyApplication.getInstance().getLoginUser().getUserName()));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);

    }

}
